package net;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Demo2_URLDownload {

    public static void main(String[] args) throws Exception {

        //第一步，创建一个要下载的 URL
        URL url = new URL("https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF");

        //第二步，通过url地址获取到这个连接
        URLConnection conn = url.openConnection();

        //第三步,获取输入流
        InputStream inputStream = conn.getInputStream();

        //第四步，创建一个写入到本地磁盘的输出流
        FileOutputStream localOS = new FileOutputStream("D://copy.gif");

        //第五步，把从网络资源的字节写入到本地磁盘
        byte[] buf = new byte[1024];
        int length;
        while((length=inputStream.read(buf))!=-1){
            localOS.write(buf,0,length);
        }

        //第六步，释放资源
        localOS.close();
        inputStream.close();
    }
}
